<template>
	<view class="gift-voucher-container">
		<!-- 分类标签 -->
		<view class="tab-section">
			<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
				@tap="switchTab(index)">
				{{ tab.name }}
				<text class="count">({{ tab.count }})</text>
			</view>
		</view>

		<!-- 礼品券列表 -->
		<scroll-view class="voucher-list" scroll-y @scrolltolower="loadMore" refresher-enabled
			@refresherrefresh="refresh" :refresher-triggered="isRefreshing">
			<!-- 空状态提示 -->
			<view class="empty-state" v-if="voucherList.length === 0 && !loading">
				<uv-icon name="empty-coupon" size="120" color="#ffdcd1"></uv-icon>
				<text class="empty-text">暂无礼品券</text>
				<text class="empty-tips">快去兑换礼品券吧~</text>
			</view>

			<view class="voucher-item glass-card" v-for="item in voucherList" :key="item.id">
				<text :class="['status', getStatusClass(item)]">{{ getStatusText(item) }}</text>
				<image class="voucher-img" :src="item.voucher_image || '/static/lyf.jpg'" mode="aspectFill"></image>
				<view class="voucher-info">
					<view class="voucher-name">{{ item.voucherName }}</view>
					<view class="voucher-desc">{{ item.voucherDesc || '暂无说明' }}</view>
					<view class="voucher-date">
						<text>有效期：{{ formatDateRange(item.startTime, item.expireTime) }}</text>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="loading" v-if="loading">加载中...</view>
			<view class="no-more" v-if="noMore && voucherList.length > 0">没有更多数据了</view>
		</scroll-view>

		<!-- 兑换按钮 -->
		<view class="float-btn" @tap="showExchangePopup">
			<uv-icon name="empty-coupon" size="36" color="#fff"></uv-icon>
			<text>兑换</text>
		</view>

		<!-- 兑换弹窗 -->
		<uv-popup ref="exchangePopup" mode="bottom" :close-on-click-overlay="true" @close="hideExchangePopup">
			<view class="exchange-popup">
				<view class="popup-title">
					<text>礼品券兑换</text>
					<text class="close-icon" @tap="hideExchangePopup">×</text>
				</view>
				<view class="popup-content">
					<input type="text" v-model="exchangeCode" placeholder="请输入兑换码" class="exchange-input" />
					<button class="confirm-btn" :disabled="!exchangeCode" @tap="handleExchange">确认兑换</button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<script>
import { formatDate, getDaysUntil } from '@/utils/date.js'

export default {
	data() {
		return {
			exchangeCode: '',
			currentTab: 0,
			tabs: [
				{ name: '未使用', count: 0 },
				{ name: '已使用', count: 0 },
				{ name: '已过期', count: 0 }
			],
			voucherList: [],
			page: 1,
			pageSize: 10,
			loading: false,
			noMore: false,
			isRefreshing: false
		}
	},
	async onLoad() {
		await this.loadVoucherCount()
		this.loadVoucherList()
	},
	methods: {
		// 加载礼品券数量
		async loadVoucherCount() {
			try {
				const res = await this.$http.get('/user/voucher/count')
				if (res) {
					this.tabs[0].count = res.unusedCount || 0
					this.tabs[1].count = res.usedCount || 0
					this.tabs[2].count = res.expiredCount || 0
				}
			} catch (e) {
				console.error('获取礼品券数量失败', e)
			}
		},

		// 加载礼品券列表
		async loadVoucherList() {
			if (this.loading || this.noMore) return
			this.loading = true
			try {
				const res = await this.$http.get(`/user/voucher?status=${this.currentTab}&pageNum=${this.page}&pageSize=${this.pageSize}`)

				if (res) {
					const list = res.items || []
					if (this.page === 1) {
						this.voucherList = list
					} else {
						this.voucherList = [...this.voucherList, ...list]
					}
					const total = res.count || 0
					this.noMore = this.voucherList.length >= total
					this.page++
				}
			} catch (e) {
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
			this.loading = false
		},

		// 切换标签
		async switchTab(index) {
			if (this.currentTab === index) return
			this.currentTab = index
			this.page = 1
			this.voucherList = []
			this.noMore = false
			await this.loadVoucherList()
		},

		// 显示兑换弹窗
		showExchangePopup() {
			this.$refs.exchangePopup.open()
		},

		// 隐藏兑换弹窗
		hideExchangePopup() {
			this.$refs.exchangePopup.close()
			this.exchangeCode = ''
		},

		// 处理兑换
		async handleExchange() {
			if (!this.exchangeCode.trim()) {
				uni.showToast({
					title: '请输入兑换码',
					icon: 'none'
				})
				return
			}

			try {
				const res = await this.$http.post(`/user/voucher/verify?code=${this.exchangeCode.trim()}`);

				if (res) {
					uni.showToast({
						title: '兑换成功',
						icon: 'none'
					})
					this.hideExchangePopup()
					// 重新加载数量和列表
					await this.loadVoucherCount()
					await this.refresh()
				}
			} catch (e) {
				uni.showToast({
					title: `${e.msg ? e.msg : '未知错误'}`,
					icon: 'none'
				})
			}
		},

		// 加载更多
		loadMore() {
			this.loadVoucherList()
		},

		// 刷新
		async refresh() {
			this.isRefreshing = true
			this.page = 1
			this.noMore = false
			await this.loadVoucherList()
			this.isRefreshing = false
		},

		// 格式化日期范围
		formatDateRange(startTime, expireTime) {
			if (!startTime) return '长期有效'
			const start = formatDate(startTime)
			if (!expireTime) return `${start} 起`
			const end = formatDate(expireTime)
			return `${start} 至 ${end}`
		},

		// 获取状态样式类
		getStatusClass(item) {
			if (this.currentTab === 1) return 'used'
			if (this.currentTab === 2) return 'expired'
			
			// 如果没有过期时间，则永久有效
			if (!item.expireTime) return 'valid'
			
			const daysLeft = getDaysUntil(item.expireTime)
			if (daysLeft <= 7) return 'expiring'
			return 'valid'
		},

		// 获取状态文本
		getStatusText(item) {
			if (this.currentTab === 1) return '已使用'
			if (this.currentTab === 2) return '已过期'
			
			// 如果没有过期时间，则永久有效
			if (!item.expireTime) return '永久有效'
			
			const daysLeft = getDaysUntil(item.expireTime)
			if (daysLeft <= 7) return `${daysLeft}天后过期`
			return '可使用'
		}
	}
}
</script>

<style lang="scss" scoped>
@import 'gift_voucher.scss';
</style>